﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using Microsoft.Phone.BackgroundAudio;
using SQLite;
using WOIM_NET.Annotations;

namespace WOIM_NET.Music
{
    public class FavoriteViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<SongModel> Items { get; private set; }

        public FavoriteViewModel()
        {
            this.Items = new ObservableCollection<SongModel>();
        }

        private int _numberOfSongs;

        public int NumberOfSongs
        {
            get { return _numberOfSongs; }
            set
            {
                if (value == _numberOfSongs) return;
                _numberOfSongs = value;
                OnPropertyChanged();
            }
        }

        public bool IsDataLoaded { get; private set; }

        public void LoadData()
        {
            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                using (var db = new SQLiteConnection(App.dbPath))
                {
                    this.Items.Clear();
                    List<FavoriteList> PlayList = db.Table<FavoriteList>().ToList<FavoriteList>();
                    foreach (FavoriteList song in PlayList)
                    {
                        this.Items.Add(new SongModel() {Artist = song.Artist, Name = song.Title, Url = song.Url, Avatar = song.Avatar, Album = song.Album, LinktoAlbum = song.LinkToAlbum });
                    }
                }
            });

            this.IsDataLoaded = true;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
